package com.ecommerce.controller;

import com.ecommerce.entity.Product;
import com.ecommerce.repository.ProductRepository;
import com.ecommerce.repository.ProductImageRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.ecommerce.service.ProductService;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import com.ecommerce.entity.ProductImage;

@RestController
@RequestMapping("/products")
@CrossOrigin(origins = "*")
public class ProductController {

    @Autowired
    private ProductRepository productRepository;
    
    @Autowired
    private ProductImageRepository productImageRepository;

    @Autowired // 自动注入ProductService
    private ProductService productService; // 商品服务

    @GetMapping
    public ResponseEntity<Map<String, Object>> getProducts(
            @RequestParam(required = false) String keyword,
            @RequestParam(required = false) String sortBy,
            @RequestParam(required = false) String sortOrder,
            @RequestParam(defaultValue = "0") int page,
            @RequestParam(defaultValue = "10") int size) {
        
        try {
            Pageable pageable;
            if (sortBy != null && sortOrder != null) {
                Sort sort = Sort.by(Sort.Direction.fromString(sortOrder.toUpperCase()), sortBy);
                pageable = PageRequest.of(page, size, sort);
            } else {
                pageable = PageRequest.of(page, size);
            }
            
            Page<Product> productPage;
            if (keyword != null && !keyword.trim().isEmpty()) {
                productPage = productRepository.searchByKeyword(keyword.trim(), pageable);
            } else {
                productPage = productRepository.findAll(pageable);
            }
            
            Map<String, Object> response = new HashMap<>();
            response.put("content", productPage.getContent());
            response.put("totalElements", productPage.getTotalElements());
            response.put("totalPages", productPage.getTotalPages());
            response.put("size", productPage.getSize());
            response.put("number", productPage.getNumber());
            
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("error", "获取商品列表失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @GetMapping("/{id}/images")
    public ResponseEntity<Map<String, Object>> getProductImages(@PathVariable Long id) {
        try {
            Optional<Product> product = productRepository.findById(id);
            if (product.isPresent()) {
                List<ProductImage> images = productImageRepository.findActiveImagesByProductId(id);
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("product", product.get());
                response.put("images", images);
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "商品不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取商品图片失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<Map<String, Object>> getProduct(@PathVariable Long id) {
        try {
            Optional<Product> product = productRepository.findById(id);
            if (product.isPresent()) {
                // 获取商品图片
                List<ProductImage> images = productImageRepository.findActiveImagesByProductId(id);
                
                // 增加浏览次数
                Product productEntity = product.get();
                productEntity.setViewCount(productEntity.getViewCount() + 1);
                productRepository.save(productEntity);
                
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("data", productEntity);
                response.put("images", images);
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> errorResponse = new HashMap<>();
                errorResponse.put("success", false);
                errorResponse.put("message", "商品不存在");
                return ResponseEntity.notFound().build();
            }
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取商品详情失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    // 创建新商品
    @PostMapping
    public ResponseEntity<Map<String, Object>> createProduct(@RequestBody Product product) {
        try {
            Product savedProduct = productRepository.save(product);
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("message", "商品创建成功");
            response.put("product", savedProduct);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "创建商品失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    // 更新商品
    @PutMapping("/{id}")
    public ResponseEntity<Map<String, Object>> updateProduct(@PathVariable Long id, @RequestBody Product product) {
        try {
            Optional<Product> existingProductOpt = productRepository.findById(id);
            if (existingProductOpt.isPresent()) {
                Product existingProduct = existingProductOpt.get();
                existingProduct.setName(product.getName());
                existingProduct.setDescription(product.getDescription());
                existingProduct.setPrice(product.getPrice());
                existingProduct.setOriginalPrice(product.getOriginalPrice());
                existingProduct.setStock(product.getStock());
                existingProduct.setSku(product.getSku());
                existingProduct.setStatus(product.getStatus());
                existingProduct.setMainImage(product.getMainImage());
                existingProduct.setCategory(product.getCategory());
                existingProduct.setBrand(product.getBrand());
                existingProduct.setModel(product.getModel());
                existingProduct.setWeightKg(product.getWeightKg());
                existingProduct.setDimensions(product.getDimensions());
                
                Product updatedProduct = productRepository.save(existingProduct);
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "商品更新成功");
                response.put("product", updatedProduct);
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "商品不存在");
                return ResponseEntity.ok(response);
            }
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "更新商品失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    // 删除商品
    @DeleteMapping("/{id}")
    public ResponseEntity<Map<String, Object>> deleteProduct(@PathVariable Long id) {
        try {
            Optional<Product> productOpt = productRepository.findById(id);
            if (productOpt.isPresent()) {
                productRepository.deleteById(id);
                Map<String, Object> response = new HashMap<>();
                response.put("success", true);
                response.put("message", "商品删除成功");
                return ResponseEntity.ok(response);
            } else {
                Map<String, Object> response = new HashMap<>();
                response.put("success", false);
                response.put("message", "商品不存在");
                return ResponseEntity.ok(response);
            }
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "删除商品失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @GetMapping("/hot")
    public ResponseEntity<Map<String, Object>> getHotProducts() {
        try {
            List<Product> hotProducts = productRepository.findHotProducts(PageRequest.of(0, 8));
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", hotProducts);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取热门商品失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @GetMapping("/new")
    public ResponseEntity<Map<String, Object>> getNewProducts() {
        try {
            List<Product> newProducts = productRepository.findNewProducts(PageRequest.of(0, 8));
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("data", newProducts);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取最新商品失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @GetMapping("/recommended")
    public ResponseEntity<Map<String, Object>> getRecommendedProducts() {
        try {
            List<Product> recommendedProducts = productRepository.findRecommendedProducts(PageRequest.of(0, 8));
            Map<String, Object> response = new HashMap<>();
            response.put("success", true);
            response.put("products", recommendedProducts);
            return ResponseEntity.ok(response);
        } catch (Exception e) {
            Map<String, Object> errorResponse = new HashMap<>();
            errorResponse.put("success", false);
            errorResponse.put("message", "获取推荐商品失败: " + e.getMessage());
            return ResponseEntity.badRequest().body(errorResponse);
        }
    }

    @GetMapping("/detail") // GET请求，路径/product/detail
    public ResponseEntity<Map<String, Object>> getProductDetail(
            @RequestParam Long productId // 请求参数：商品ID
    ) {
        Map<String, Object> result = productService.getProductDetail(productId); // 调用服务获取商品详情
        return ResponseEntity.ok(result); // 返回商品详情
    }
} 